This unit covers the critical early stages of a machine learning project: the methodology framework, exploratory data analysis (EDA), data cleaning, categorical encoding, and feature scaling. These steps typically consume 60–80% of project time, and they set an upper limit on how well the later stages can perform. A model trained on poorly prepared data will not give reliable results, no matter which algorithm is used. By the end of this unit, you will be able to take raw, messy real-world data and prepare it correctly for downstream machine learning algorithms.
Real machine learning projects follow a structured methodology rather than applying algorithms directly to whatever data happens to be available. CRISP-ML(Q) is a widely used framework of this kind. It divides a project into six phases:
Business and Data Understanding
This phase ensures project feasibility before significant resources are committed. The main tasks include identifying the ML application scope and business success criteria, defining measurable KPIs, assessing the availability of time, technology, and human resources, and verifying that sufficient high-quality data exists. If the data is inadequate, the team may need to redesign the data collection approach. For example, consider a spam detection project. The business success criterion might be "build an effective spam filter." The KPIs could be specified as "achieve 95% accuracy with less than 1% false positive rate on held-out validation data." These measurable targets allow the team to determine whether the model meets the business requirements.Data Engineering (Data Preparation)
This is the phase where the current unit primarily lives. Tasks include data selection and discarding low-quality samples, cleaning missing values and outliers, feature engineering (creating derived features), encoding categorical variables, and applying standardization or normalization. This phase often takes 60–80% of the total project time. Skipping it properly will ruin every downstream model, regardless of which algorithm you choose.ML Model Engineering
In this phase, you apply the algorithms you will learn throughout this course. The work involves translating the business problem into a specific ML task such as classification, regression, or clustering. You then perform model selection, specialization, and training. It is also essential to collect metadata about the experiment, including the algorithm used, train/validation/test splits, hyperparameters, and the runtime environment. This phase often requires stepping back to the data engineering phase for additional feature work.Quality Assurance
This phase involves offline testing on a held-out test set. You validate model performance against the KPIs defined in Phase 1 and analyze whether the business objectives will actually be achieved. Every evaluation outcome must be carefully documented to support decision-making about whether the model is ready for production.Deployment
Deployment exposes the model to real users. This can take many forms, such as interactive dashboards, pre-computed predictions, plug-in components, or web service API endpoints. You must also define the update and retraining process. Examples of deployment include a Flask/FastAPI REST endpoint, mobile-app integration, or an automated weekly report pipeline.Monitoring and Maintenance
Model performance tends to decay over time due to "data drift" or "concept drift" — changes in the data distribution or the underlying relationships in the problem. Therefore, you must track live prediction quality and distribution shifts. The model should be retrained on a schedule or whenever KPI thresholds are breached. Additionally, every prediction and its corresponding ground truth should be logged to support post-hoc audits and future improvements.Before preprocessing data, it is important to understand the type of each feature. Different feature types require different preprocessing and encoding methods.
| Type | Description | Examples |
|---|---|---|
| Nominal (Categorical) | Unordered categories | Hair color, marital status, customer_id |
| Binary | Two nominal categories | is_smoker, medical_test_result (+ve / −ve) |
| Ordinal | Ordered categories | Shirt size (S/M/L/XL), grades, customer_satisfaction |
| Numerical | Continuous or discrete numbers | Age, temperature, salary, number_of_dependents |
Missing values are common in real-world datasets. There are two general approaches: removing the affected rows or columns, or imputing a replacement value. The choice depends on how much data is missing and whether the missing values are informative. The two tabs below show how each approach is applied in pandas:
Removal — The simplest approach is to remove the offending rows or columns. Pandas provides several operations for this purpose:
Imputation replaces missing values with estimated values. Common imputation methods include replacing missing numerical values with the mean, median, or mode of the column, or using more sophisticated techniques like KNN imputation. We will explore these methods in more detail in later units.
Most ML algorithms work with numerical input rather than categorical values represented as text. Therefore, categorical variables need to be converted into numerical representations. Three commonly used techniques are one-hot encoding, ordinal encoding, and label encoding.
Create a new binary dummy feature for each unique value in the original categorical feature. For a color feature with values {blue, green, red}:
| Original color | blue | green | red |
|---|---|---|---|
| blue | 1 | 0 | 0 |
| green | 0 | 1 | 0 |
| red | 0 | 0 | 1 |
One-hot encoding is suitable for nominal features where there is no natural ordering. Be aware that this approach increases the number of columns in your dataset by the number of unique categories minus one (to avoid multicollinearity).
Ordinal encoding is used when the categories have a meaningful order. The desired ordering can be specified explicitly.
Label encoding is used for the target class labels (y), not for input features. It maps class names to integer values such as 0, 1, 2, and so on.
Label encoding should not be used for input features unless the feature is ordinal, because the arbitrary integer assignment might imply an ordering that does not actually exist.
Feature scaling is important when features have very different numerical ranges. For example, if Age ranges from 18–65 while Salary ranges from $20k–$300k, distance-based algorithms such as kNN, SVM, and clustering can allow Salary to dominate the distance calculation. Scaling puts features on comparable scales so that differences in their original numerical ranges do not have an undue effect on the model.
Scales every feature to [0, 1] using the per-feature min and max:
Centers each feature column at mean 0 with standard deviation 1 (parameters of the standard normal distribution):
Standardization does not change the shape of a distribution, nor convert a non-normal distribution to normal.
| Situation | Prefer Normalization | Prefer Standardization |
|---|---|---|
| Distance-based algorithms (kNN, clustering) | ✅ Usually | Also valid |
| Bounded output range needed (e.g., image pixels) | ✅ Always | — |
| Outliers present in the data | — | ✅ Less sensitive |
| Neural Networks or PCA | — | ✅ Required / Preferred |
| Gradient-descent optimization (e.g., LogReg) | — | ✅ Usually |
Before preparing features for downstream modeling, we first need to understand what is present in the raw data. Exploratory Data Analysis (EDA) helps identify issues such as missing values, outliers, imbalance, and correlations.
EDA can be performed through two complementary tracks: manual EDA and automated EDA.
Manual EDA
Manual exploration can be performed using:
Automated EDA
Automated tools can provide a broader initial overview of the dataset. Examples include:
For each real-world feature, classify it as Nominal / Binary / Ordinal / Numerical. Click the reveal button below each scenario.
Scenario A: A "Level_of_Education" column with values {High School, Bachelor, Masters, PhD}.
Scenario B: A "State_of_Residence" column with values {CA, TX, NY, FL, …}.
Scenario C: An "Annual_Income_USD" column storing exact salaries.
For each case below, decide whether scaling is required, and between Min-Max vs. Z-score standardization. Reveal each answer separately.
Case 1: Training a kNN classifier on features Age (years), Income (USD), and Height (cm).
Case 2: Training a Random Forest classifier on the same three features.
Case 3: Feeding features into a PCA dimensionality-reduction step before classification.
Given the ages {26, 28, 34, 38}: normalize each value using Min-Max scaling so the outputs lie in [0, 1].
Step 1: Identify the range.
Step 2: Apply the formula to each point.
| Raw age | Calculation | Normalized x' |
|---|---|---|
| 26 | (26−26)/12 | 0.000 |
| 28 | (28−26)/12 | 0.167 |
| 34 | (34−26)/12 | 0.667 |
| 38 | (38−26)/12 | 1.000 |
Check: min maps to 0, max maps to 1 ✓.
Given salaries {$100,000; $140,000; $150,000; $300,000}. Compute the sample mean, sample standard deviation, and then the Z-score for each value.
Step 1: Compute sample mean.
Step 2: Compute sample standard deviation (divide by n−1).
Step 3: Apply Z = (x − μ) / σ per salary.
| Salary ($K) | Z |
|---|---|
| 100 | −0.827 |
| 140 | −0.370 |
| 150 | −0.257 |
| 300 | +1.454 |
Check: Mean of Z-scores is 0; sample SD ≈ 1 ✓. Notice the $300K salary pulls the mean up and the Z of +1.45 indicates it is not a massive outlier despite looking like one — a strength of standardization.
You are given 5 test scores: {55, 62, 70, 78, 95}.
(a) Min=55, Max=95, range=40.
| x | Min-Max |
|---|---|
| 55 | 0.000 |
| 62 | 0.175 |
| 70 | 0.375 |
| 78 | 0.575 |
| 95 | 1.000 |
(b) μ = 72, σ ≈ 15.427.
| x | Z |
|---|---|
| 55 | −1.10 |
| 62 | −0.65 |
| 70 | −0.13 |
| 78 | +0.39 |
| 95 | +1.49 |
(c) Min-Max of 70 is 0.375 because 70 sits 37.5% of the way from 55 to 95. The Z of 70 is negative because 70 is slightly below the mean of 72. The two scalers answer different questions: "position inside observed range" vs. "deviation from mean in SD units."
A dataset has the following features. For each, name the correct encoding strategy and justify in one sentence.
country_of_birth — 42 unique country names.satisfaction_rating — "Very Unsatisfied" / "Unsatisfied" / "Neutral" / "Satisfied" / "Very Satisfied".customer_churn — target variable "Stayed" / "Churned".monthly_charges_usd — continuous dollar amounts.A dataset of 5,000 patients has the following missingness patterns. Recommend a concrete handling strategy for each column:
patient_zip_code: 47% missing.resting_blood_pressure: 1.2% missing; no obvious pattern of missingness.has_diabetes: 3.1% missing. You suspect diabetic patients forgot to tick the "Yes" box more often than non-diabetics did.Answer all 5 questions. Click an option for instant feedback.
Your score: 0 / 5
fit(train) then transform(train) and transform(test) separately.